﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Text.RegularExpressions;
namespace Lib.Integration
{
    public class IntegrateAllXML
    {
        public static void IntegrateXMLToSQL(string CateColName, string Table, string sqlConnection, string fPath)
        {
            System.Data.SqlClient.SqlConnection scon = new System.Data.SqlClient.SqlConnection(sqlConnection);
            System.Data.SqlClient.SqlCommand scmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM " + Table, scon);
            System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter(scmd);
            System.Data.SqlClient.SqlCommandBuilder scb = new System.Data.SqlClient.SqlCommandBuilder(sda);

            System.Data.DataTable tbl = new System.Data.DataTable();
            sda.FillSchema(tbl, System.Data.SchemaType.Source);

            sda.InsertCommand = scb.GetInsertCommand();
            IntegrateDataFromFiles(CateColName, fPath, ref tbl);
            sda.Update(tbl);
        }

        public static string ConvertIndexCate(string sTitle)
        {
            if (string.IsNullOrEmpty(sTitle))
                return "";
            string strTitle = sTitle.Trim().Replace(' ', '-');
            string[] arrChr = new string[] { "~", "`", "!", "@", "#", "$", "%", "^", "*", "(", ")", "_", "+", "=", "\\", "-", ";", ":", ",", ".", "<", ">", "?", "/", "'", "\"", "\"" };
            for (int i = 0; i < arrChr.Length; i++)
            {
                strTitle = strTitle.Replace(arrChr[i], "-");
            }
            strTitle = strTitle.Replace("&", "va");
            strTitle = strTitle.ToLower();
            strTitle = Regex.Replace(strTitle, "\\s", string.Empty);
            strTitle = Regex.Replace(strTitle, "á|à|ạ|ả|ã|ă|ắ|ằ|ặ|ẳ|ẵ|â|ấ|ầ|ậ|ẩ|ẫ", "a");
            strTitle = Regex.Replace(strTitle, "đ", "d");
            strTitle = Regex.Replace(strTitle, "Đ", "d");
            strTitle = Regex.Replace(strTitle, "ó|ò|ọ|ỏ|õ|ơ|ớ|ờ|ợ|ở|ỡ|ô|ố|ồ|ộ|ổ|ỗ", "o");

            strTitle = Regex.Replace(strTitle, "ú|ù|ụ|ủ|ũ|ư|ứ|ừ|ự|ử|ữ", "u");
            strTitle = Regex.Replace(strTitle, "é|è|ẹ|ẻ|ẽ|ê|ế|ề|ệ|ể|ễ", "e");
            strTitle = Regex.Replace(strTitle, "í|ì|ị|ỉ|ĩ", "i");
            strTitle = Regex.Replace(strTitle, "ý|ỳ|ỵ|ỷ|ỹ", "y");
            while (strTitle[0] == '-')
            {
                strTitle = strTitle.Remove(0, 1);
            }
            while (strTitle[strTitle.Length - 1] == '-')
            {
                strTitle = strTitle.Remove((strTitle.Length - 1), 1);
            }
            int intI = 0;
            while (intI < strTitle.Length)
            {
                if (strTitle[intI] == '-' && strTitle[intI + 1] == '-')
                {
                    strTitle = strTitle.Remove(intI, 1);
                    intI--;
                }
                intI++;
            }
            char FirstChar = strTitle[0];

            strTitle = FirstChar.ToString().ToUpper() + strTitle.Remove(0, 1);
            return strTitle;
        }

        static void IntegrateDataFromFiles(string categoryColumnName, string fPath, ref System.Data.DataTable tbl)
        {
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(fPath);
            if (di.Exists)
            {
                foreach (System.IO.DirectoryInfo d in di.GetDirectories())
                    IntegrateDataFromFiles(categoryColumnName, d.FullName, ref tbl);
                foreach (System.IO.FileInfo f in di.GetFiles())
                {
                    System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
                    xdoc.Load(f.FullName);
                    System.Xml.XmlNodeList xlist = xdoc.SelectNodes("/Pages");
                    System.Data.DataRow dr = tbl.NewRow();
                    foreach (System.Xml.XmlNode xnode in xlist)
                    {
                        if (xnode.Name == "Pages")
                            foreach (System.Xml.XmlNode x in xnode)
                            {
                                try
                                {
                                    dr[x.Name] = x.InnerText;
                                }
                                catch { }
                            }
                        else
                            try
                            {
                                dr[xnode.Name] = xnode.InnerText;
                            }
                            catch { }
                    }

                    if (!string.IsNullOrEmpty(categoryColumnName))
                        dr[categoryColumnName] = xlist[0]["category"].InnerText;
                    dr["News_Status"] = 1;
                    dr["PCateID"] = "";
                    dr["News_Type"] = 1;
                    dr["News_Subtitle"] = dr["News_Title"];
                    dr["News_Intro"] = "";
                    dr["News_DatePost"] = DateTime.Now;
                    dr["News_Source"] = xlist[0]["url"].InnerText;
                    dr["News_Author"] = "";
                    dr["AdminPost"] = "autotin";
                    dr["AdminEdit"] = "autotin";
                    dr["AdminActive"] = "autotin";
                    dr["News_IsSpecial"] = false;
                    dr["News_IsHome"] = true;
                    dr["News_IsNewsImage"] = false;
                    dr["News_Focus"] = false;
                    dr["News_IsTopCate"] = false;
                    dr["News_IsEvent"] = false;
                    dr["News_IsFeedBack"] = true;
                    dr["News_Hits"] = 0;
                    dr["News_Votes"] = 0;
                    dr["News_Order"] = 1;
                    dr["New_IsConcern"] = "";
                    dr["Lang"] = "vn";
                    dr["News_Pos"] = 1;
                    dr["News_Keyword"] = "";
                    dr["News_TimeStart"] = DateTime.Now;
                    dr["News_TimeEnd"] = DateTime.Now;
                    dr["Product_Id"] = 0;
                    dr["News_CateParentID"] = "";
                    dr["News_Royalties"] = "";
                    dr["News_Link"] = ConvertIndexCate(dr["News_Title"].ToString());
                    if (dr["News_Content"] != null && dr["News_Content"].ToString() != "")
                    {
                        string url = dr["News_Source"].ToString();
                        url = url.Replace("http://","");
                        string[] urllst = url.Split( new char[] { '/', '\\'},StringSplitOptions.RemoveEmptyEntries);
                        if(urllst.Length>0)
                            url = urllst[0];
                        dr["News_Content"] = dr["News_Content"].ToString().Replace("src=\"/", "src=\"http://" + url + "/").Replace("src=/", "src=http://" + url + "/").Replace("href=\"/", "href=\"http://" + url + "/").Replace("href=/", "href=http://" + url + "/");
                    }
                    if(dr["News_Title"]!=null && dr["News_Title"].ToString().Trim()!="")
                        tbl.Rows.Add(dr);
                    f.Delete();
                }
            }
        }
    }
}
